package com.zmn.oms.task.job.third.tmall;

import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.third.taobao.TaobaoTmcConstants;
import com.zmn.oms.third.taobao.service.TmallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 类描述：定时拉取天猫订单预警信息任务
 *
 * @author LiangHailong
 * @date 2019/08/01 15:07
 */
@LTS
@Slf4j
public class OrderWarnJob {
    @Autowired
    private TmallService tmallService;

    @Resource
    TaskManager taskManager;

    /**
     * 每隔12分钟，拉取15分钟内的天猫订单预警信息
     */
    @PostConstruct
    void init() {
        Job job = new Job();
        job.setTaskId(TaskConsts.TASK_ID_TMALL_ORDER_WARN);
        job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_TMALL_ORDER_WARN);
        job.setCronExpression("0 /12 * * * ?");
        job.setReplaceOnExist(true);
        ResultDTO result = taskManager.submitTask(job);
        if (!result.getStatusBool()) {
            log.error("#oms#orderwarnjob# job submit fail...");
        }
    }

    /**
     * 拉取15分钟内的天猫订单预警信息
     * @param job
     * @return
     */
    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_TMALL_ORDER_WARN)
    public Result runWorkJob(Job job) {
        if (!TaobaoTmcConstants.POWER_ON) {
            log.info("【{}】<订单拉取> 该功能没有开启。", TaobaoTmcConstants.NAME_TMALL);
            return null;
        }

        Date endDate = DateUtil.getNow();
        try {
            tmallService.pullOrderWarns(endDate);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        int limit = 1000 * 60 * 15;
        Date startDate = new Date(endDate.getTime() - limit);
        String startDateStr = DateUtil.dateFormatToString(startDate, DateUtil.FORMAT_DEFAULT);
        String endDateStr = DateUtil.dateFormatToString(endDate, DateUtil.FORMAT_DEFAULT);

        log.info("#oms#orderwarnjob# 拉取15分钟之内的天猫订单预警任务执行成功 ！{}-{}", startDateStr, endDateStr);
        return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
    }
}
